package com.jieshuibao.controller;


import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.config.enumtype.ResponseCode;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.common.utils.Md5Util;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.UserDealRecord;
import com.jieshuibao.model.db.Version;
import com.jieshuibao.model.domain.AllArticleResponse;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.IosVerifyReq;
import com.jieshuibao.model.domain.WithinRequest;
import com.jieshuibao.service.IosWithinService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserDealRecordService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.VersionService;
import com.jieshuibao.util.AesUtil;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.util.PayCommonUtil;

@Controller
@RequestMapping(value = "/within")
public class WithinController {
	@Resource
	private RedisService redisService;
	@Resource
	private UserService userService;
	@Resource
	private VersionService versionService;
	@Resource
	private UserDealRecordService userDealRecordService;
	
	@Resource
	private IosWithinService IosWithinService;
	
	@RequestMapping(value = "/purchase", method = RequestMethod.POST)
	@ResponseBody
	public Object queryAllArticle(HttpServletRequest request,
			@RequestBody WithinRequest wthinRequest) {

		AllArticleResponse allArticleResponse = new AllArticleResponse();
		try {
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);
				if (cookieUser != null) {
					String phoneNumber = cookieUser.getPhoneNumber();
					if (phoneNumber != null) {
							double money = wthinRequest.getMoney();
							String uuid1 = UUIDGenerator.getUUID();
				    		UserDealRecord userDealRecord1 = new UserDealRecord();
				    		Date date = new Date();
				    		userDealRecord1.setUuid(uuid1);
				        	userDealRecord1.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
				        	userDealRecord1.setBusinessNo(phoneNumber);
				        	userDealRecord1.setCreateDate(date);
				        	userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_WITHIN);
				        	userDealRecord1.setPaySucTime(date);
				        	userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_WITHIN);
				        	userDealRecord1.setRealPrice(money);
				        	userDealRecord1.setStatus(PayCommonUtil.PAYPENDING_STATUS);
				        	userDealRecord1.setSum(money);
				        	userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
				        	userDealRecord1.setUserId(phoneNumber);
				        	userDealRecordService.addUserDealRecord(userDealRecord1);
					} else {
						// 重新登录
						allArticleResponse.setCode("2");
						allArticleResponse.setDes("重新登录");
					}
				} else {
					// 重新登录
					allArticleResponse.setCode("2");
					allArticleResponse.setDes("重新登录");
				}
			} else {
				// 重新登录
				allArticleResponse.setCode("2");
				allArticleResponse.setDes("重新登录");
			}
		} catch (Exception e) {
			e.printStackTrace();
			allArticleResponse.setCode("0");
			allArticleResponse.setDes("系统繁忙");
		}
		return allArticleResponse;
	}

	@RequestMapping(value = "/ios", method = RequestMethod.POST)
	@ResponseBody
	public Object iosWithin(HttpServletRequest request,
			@RequestBody WithinRequest wthinRequest) {

		AllArticleResponse allArticleResponse = new AllArticleResponse();
		try {
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);
				if (cookieUser != null) {
					String phoneNumber = cookieUser.getPhoneNumber();
					if (phoneNumber != null) {
						List<Version> versionCode = versionService.getVersionCode();
						Version version = versionCode.get(0);
							Integer iosUpCode = version.getIosUpCode();
							
							int iosCode2 = wthinRequest.getIosCode();
							double money = wthinRequest.getMoney();
							if(iosCode2>iosUpCode){
								User user = userService.getUserByPhoneNumber(phoneNumber);
								Double balance = user.getBalance();
								User user2 = new User();
								user2.setPhoneNumber(phoneNumber);
								user2.setBalance(balance+money);
								userService.updateUserWithin(user2, money);
								allArticleResponse.setCode("1");
								allArticleResponse.setDes("成功");
							}else {
								String uuid1 = UUIDGenerator.getUUID();
					    		UserDealRecord userDealRecord1 = new UserDealRecord();
					    		Date date = new Date();
					    		userDealRecord1.setUuid(uuid1);
					        	userDealRecord1.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
					        	userDealRecord1.setBusinessNo(phoneNumber);
					        	userDealRecord1.setCreateDate(date);
					        	userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_WITHIN);
					        	userDealRecord1.setPaySucTime(date);
					        	userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_WITHIN);
					        	userDealRecord1.setRealPrice(money);
					        	userDealRecord1.setStatus(PayCommonUtil.PAYPENDING_STATUS);
					        	userDealRecord1.setSum(money);
					        	userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
					        	userDealRecord1.setUserId(phoneNumber);
					        	userDealRecordService.addUserDealRecord(userDealRecord1);
					        	allArticleResponse.setCode("1");
								allArticleResponse.setDes("成功");
							}
							
					} else {
						// 重新登录
						allArticleResponse.setCode("2");
						allArticleResponse.setDes("重新登录");
					}
				} else {
					// 重新登录
					allArticleResponse.setCode("2");
					allArticleResponse.setDes("重新登录");
				}
			} else {
				// 重新登录
				allArticleResponse.setCode("2");
				allArticleResponse.setDes("重新登录");
			}
		} catch (Exception e) {
			e.printStackTrace();
			allArticleResponse.setCode("0");
			allArticleResponse.setDes("系统繁忙");
		}
		return allArticleResponse;
	}
	@RequestMapping(value = "/review", method = RequestMethod.POST)
	@ResponseBody
	public Object isReview(HttpServletRequest request,
			@RequestBody WithinRequest wthinRequest) {

		AllArticleResponse allArticleResponse = new AllArticleResponse();
		try {
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);
				if (cookieUser != null) {
					String phoneNumber = cookieUser.getPhoneNumber();
					if (phoneNumber != null) {
						List<Version> versionCode = versionService.getVersionCode();
						Version version = versionCode.get(0);
							Integer iosUpCode = version.getIosUpCode();
							
							int iosCode2 = wthinRequest.getIosCode();
							
							if(iosCode2>iosUpCode){
								allArticleResponse.setCode("1");
								allArticleResponse.setDes("成功");
							}else {
								allArticleResponse.setCode("3");
								allArticleResponse.setDes("不在审核中");
							}
							
					} else {
						// 重新登录
						allArticleResponse.setCode("2");
						allArticleResponse.setDes("重新登录");
					}
				} else {
					// 重新登录
					allArticleResponse.setCode("2");
					allArticleResponse.setDes("重新登录");
				}
			} else {
				// 重新登录
				allArticleResponse.setCode("2");
				allArticleResponse.setDes("重新登录");
			}
		} catch (Exception e) {
			e.printStackTrace();
			allArticleResponse.setCode("0");
			allArticleResponse.setDes("系统繁忙");
		}
		return allArticleResponse;
	}
	
	
	@RequestMapping(value="/ios/setIapCertificate")
	@ResponseBody
	public Object iosVerify(HttpServletRequest request,@RequestBody IosVerifyReq req ){
		BaseRes<String> res = new BaseRes<String>();
		
		try {
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			String userId = cookieUser.getPhoneNumber();
			String receipt = req.getReceipt();
			double money = req.getMoney();
			
			String uuid = req.getUuid();
			if (StringUtils.isBlank(receipt)||StringUtils.isBlank(uuid)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			
			String md5 = Md5Util.Md5(receipt);
			boolean withInIos = IosWithinService.isWithInIos(md5);
			if (withInIos) {
				res.setCode(BaseRes.SUCCESS_CODE);
				res.setDes("不能重复购买！");
				return res;
			}
			try {
				String rquestDecryData = AesUtil.rquestDecryData(uuid, userId);
				if (StringUtils.isNotBlank(rquestDecryData)&&userId.equals(rquestDecryData)) {
					userId=rquestDecryData;
				}else {
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("参数错误！"+ResponseCode.RESPONSE_CODE_1004.getCode());
					return res;
				}
				
				
			} catch (Exception e) {
				e.printStackTrace();
				res.setCode(BaseRes.FAIL_CODE);
				res.setDes(BaseRes.FAIL_CODE+ResponseCode.RESPONSE_CODE_1004.getCode());
				return res;
			}
			return IosWithinService.checkIosWithIn(receipt, userId, money);
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_CODE+ResponseCode.RESPOSNE_CODE_1005.getCode());
			return res;
		}
	}

}
